//=============================================================
// 创建人:            ssd
// 创建时间:          11/20/2024 10:28:30 AM
// 邮箱：             1292934053@qq.com
//==============================================================
using LF.Common;
using LF.Domain.Entities;
using LF.Domain.Helper;
using LF.Shared.Dtos.Input;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LF.Domain.Services.Iml
{
    public class DeptmentManagerService : IDeptmentManagerService
    {
        public List<Deptment> All(int index, int pageSize, string? key)
        {
            var query = FreeSqlHelper.DbContext.Queryable<Deptment>();
            if (!key.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.DeptName.Contains(key) || p.DeptCode.Contains(key));
            }
            var list = query.Where(p => !p.IsDelete)
                .OrderBy(p => p.OrderNo)
                .OrderByDescending(p => p.UpdateTime)
                .Page(index, pageSize)
                .ToList();
            return list;
        }

        public long Count(string? key)
        {
            var query = FreeSqlHelper.DbContext.Queryable<Deptment>();
            if (!key.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.DeptName.Contains(key) || p.DeptCode.Contains(key));
            }
            return query.Where(p => !p.IsDelete).Count();
        }

        public List<Deptment> GetDeptTree()
        {
            var allDepts = GetAll();
           
            var rootDepts = allDepts.Where(d => !d.SupDeptId.HasValue)
                .OrderBy(d => d.OrderNo)
                .ToList();
            
            foreach (var dept in rootDepts)
            {
                BuildDeptTree(dept, allDepts);
            }
            
            return rootDepts;
        }

        private void BuildDeptTree(Deptment parent, List<Deptment> allDepts)
        {
            parent.Children = allDepts.Where(d => d.SupDeptId == parent.Id)
                .OrderBy(d => d.OrderNo)
                .ToList();
            foreach (var child in parent.Children)
            {
                BuildDeptTree(child, allDepts);
            }
        }

        public List<Deptment> GetAll()
        {
            return FreeSqlHelper.DbContext.Queryable<Deptment>()
                .Where(p => !p.IsDelete)
                .OrderBy(p => p.OrderNo)
                .ToList();
        }

        public List<Deptment> GetDeptWithChildren(Guid deptId)
        {
            var dept = FreeSqlHelper.DbContext.Queryable<Deptment>()
                .Where(p => p.Id == deptId && !p.IsDelete)
                .First();

            if (dept == null)
                return new List<Deptment>();

            var result = new List<Deptment> { dept };
            var children = GetChildDepts(deptId);
            result.AddRange(children);
            return result;
        }

        private List<Deptment> GetChildDepts(Guid parentId)
        {
            var children = FreeSqlHelper.DbContext.Queryable<Deptment>()
                .Where(p => p.SupDeptId == parentId && !p.IsDelete)
                .ToList();

            var result = new List<Deptment>(children);
            foreach (var child in children)
            {
                var grandChildren = GetChildDepts(child.Id);
                result.AddRange(grandChildren);
            }
            return result;
        }

        public bool CheckDeptCodeExists(string deptCode, Guid? excludeId = null)
        {
            var query = FreeSqlHelper.DbContext.Queryable<Deptment>()
                .Where(p => p.DeptCode == deptCode && !p.IsDelete);
                
            if (excludeId.HasValue)
            {
                query = query.Where(p => p.Id != excludeId.Value);
            }
            
            return query.Any();
        }

        public string GenerateDeptCode(Guid? parentId)
        {
            // 获取父部门编码
            string parentCode = "";
            if (parentId.HasValue)
            {
                var parent = FreeSqlHelper.DbContext.Queryable<Deptment>()
                    .Where(p => p.Id == parentId.Value && !p.IsDelete)
                    .First();
                if (parent != null)
                {
                    parentCode = parent.DeptCode;
                }
            }

            // 获取同级部门数量
            var count = FreeSqlHelper.DbContext.Queryable<Deptment>()
                .Where(p => p.SupDeptId == parentId && !p.IsDelete)
                .Count();

            // 生成三位数编码
            var newCode = (count + 1).ToString().PadLeft(3, '0');
            
            // 组合完整编码
            return $"{parentCode}{newCode}";
        }
    }
}

